// Copyright 2011 Bryan McKelvey

/**
 * @fileoverview Main options page script.
 * @author bryan.mckelvey@gmail.com (McKelvey Bryan)
 */

/**
 * Options script functions.
 * @namespace Options script functions.
 */
var Options = (function() {
  /**
   * Load options to options page from local storage
   */
  function load() {
    for (var key in localStorage) {
      var value = JSON.parse(localStorage[key]);
      var $input = $('#options #' + key).eq(0);

      switch ($input.attr('type')) {
        case 'checkbox':
          $input.attr('checked', value);
          break;
        default:
          $input.val(value);
          break;
      }
    }
  }

  load();
  
  return {
    /**
     * Saves options chosen on options page.
     */
    save: function() {
      $('#options input[id]').each(function() {
        var $input = $(this);
        var key = $input.attr('id');
        var value;

        // Get value based on type of input
        switch ($input.attr('type')) {
          case 'checkbox':
            value = $input.attr('checked');
            break;
          default:
            value = $input.val();
            break;
        }

        // Save in local storage
        localStorage[key] = JSON.stringify(value);
      });
      alert('Saved successfully! ESPN.com tabs will reflect the changes you\'ve made on the next refresh.');
      window.close();
    }
  };
}());